<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          size="small"
          style="width: 240px"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          size="small"
          style="width: 240px"
          placeholder="请输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          size="small"
          style="width: 240px"
          placeholder="请输入手机号码"
        ></el-input>
      </el-form-item>
      <el-form-item label="注册时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="mini"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
          >
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            size="mini"
            plain
            icon="el-icon-edit"
            :disabled="buttonState.editDisabled"
            @click="handleUpdate()"
          >
            修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            size="mini"
            plain
            icon="el-icon-delete"
            :disabled="buttonState.delDisabled"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </el-col>
        <right-toolbar @queryTable="getData"></right-toolbar>
      </el-row>
    </div>
    <el-table :data="userData" v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column label="序号" width="50" align="center">
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="用户名"
        prop="username"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="姓名"
        prop="realName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="性别" :show-overflow-tooltip="true" width="60">
        <template slot-scope="scope">
          {{
            scope.row.gender == '1'
              ? '男'
              : scope.row.gender == '0'
              ? '女'
              : '保密'
          }}
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="age" width="50" />
      <el-table-column label="手机号码" prop="phone" width="120" />
      <el-table-column label="用户权限" prop="roles[0].roleName" width="120" />
      <el-table-column
        label="上次登录时间"
        prop="loginTime"
        width="180"
        align="center"
      />
      <el-table-column
        label="注册时间"
        prop="createdTime"
        width="180"
        align="center"
      />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row.userId)"
          >
            <span v-if="scope.row.roleLevel != 0">修改</span>
            <span v-else>查看</span>
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.userId)"
            v-if="scope.row.userId != 1"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.limit"
      @pagination="getData"
    />

    <el-dialog :title="title" :visible.sync="open" width="450px">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            show-word-limit
            minlength="4"
            maxlength="16"
            :readonly="!showPassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="showPassword">
          <el-input
            type="password"
            v-model="form.password"
            placeholder="请输入用户密码"
            show-password
            minlength="6"
            maxlength="18"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="realName">
          <el-input
            v-model="form.realName"
            placeholder="请输入用户姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择用户性别" style="width: 100%">
            <el-option
              v-for="item in gender"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户年龄" prop="age">
            <el-input
              v-model="form.age"
              placeholder="请输入用户年龄"
              minlength="1"
              maxlength="3"
              show-word-limit
            ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择用户角色" style="width: 100%">
            <el-option
              v-for="item in perRoles"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" :disabled="buttonState.submitDisabled" @click.native="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'User',
  data() {
    var checkUsername = (rule, value, callback) => {
			if (!value) {
				callback(new Error('请输入用户名'))
			} else {
				this.getRequest(`/manage/user/${this.optionType}/${this.form.username}`).then(resp => {
					if (resp.status === 21) {
						callback(new Error('用户名已存在'));
					} else {
						callback();
					}
				});
			}
		};
    return {
      queryParams: {
        page: 1,
        limit: 10,
        username: undefined,
        realName: undefined,
        gender: undefined,
      },
      // 注册时间范围
      dateRange: [],
      userData: null,
      totalCount: 0,
      loading: false,
      buttonState: {
        editDisabled: true,
        delDisabled: true,
        submitDisabled: false,
      },
      form: {},
      title: '',
      open: false,
      showPassword: undefined,
      perRoles: [],
      userIds: [],
      optionType: undefined,
      rules: {
        username: [
					{ min: 4, max: 16, message: '用户名长度在 4 到 16 个字符', trigger: 'blur'},
					{ pattern: /^[a-zA-Z]\w*$/, message: '用户名须以字母开头，字母数字下划线组合', trigger: 'blur'},
					{ required: true, validator: checkUsername, trigger: 'blur' }
				],
        password: [
					{ required: true, message: "请输入用户密码", trigger: 'blur'},
					{ min: 6, max: 18, message: '密码长度在 6 到 18 个字符', trigger: 'blur'}
				],
        realName: [
          { required: true, message: "请输入用户姓名", trigger: 'blur'},
        ],
        roleId: [
          { required: true, message: "请选择用户角色", trigger: 'blur'},
        ],
        age: [
          { pattern: /^\d{1,3}$/, message: '年龄范围在0~999', trigger: 'blur'}
        ]
      },
    }
  },
  created() {
    this.getData();
  },
  methods: {
    // 删除用户
    handleDelete(userId) {
      this.$confirm('此操作将永久删除用户是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let id = userId || this.userIds;
        this.deleteRequest(`/manage/user/${id}`).then(() => {
          // 判断删除之后页码数是否发生变化
          let totalPage = 0; 
          if (id instanceof Array) {
            // 批量删除
            totalPage = Math.ceil((this.totalCount - id.length) / this.queryParams.limit); // 剩余数据总页数
            this.totalCount -= id.length;
          } else {
            // 单条删除
            totalPage = Math.ceil((this.totalCount - 1) / this.queryParams.limit); // 剩余数据总页数
            this.totalCount -= 1;
          }

          this.queryParams.page = this.queryParams.page > totalPage ? totalPage : this.queryParams.page
          this.queryParams.page = this.queryParams.page < 1 ? 1 : this.queryParams.page

          this.getData()
        })
      }).catch(() => {});
    },
    // 表单提交
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.buttonState.submitDisabled = true;
          if (!this.form.userId) {
            // 新增
            this.postRequest('/manage/user/', this.form).then(() => {
              this.getData();
              this.buttonState.submitDisabled = false;
              this.open = false;
            }).catch(() => {
              this.buttonState.submitDisabled = false;
            });
          } else {
            // 修改
            this.putRequest('/manage/user/', this.form).then(() => {
              this.getData();
              this.buttonState.submitDisabled = false;
              this.open = false;
            }).catch(() => {
              this.buttonState.submitDisabled = false;
            });
          }
        }
      })
    },
    // 关闭对话框
    cancel() {
      this.open = false;
      setTimeout(() => {
        this.reset();
      }, 200)
    },
    // 打开修改对话框
    handleUpdate(userId) {
      let uId = userId || this.userIds[0];
      let result = undefined;
      if (uId == '1') {
        // 超级管理员
        this.getPerRoleAdmin();
      } else {
        this.getPerRoles();
      }
      
      this.getRequest(`/manage/user/${uId}`).then(resp => {
        if (resp) {
          this.reset()
          this.title = '修改用户';
          this.open = true;
          this.showPassword = false;
          this.form = resp.data;
          this.optionType = 'edit';
        }
      });
    },
    // 打开新增对话框
    handleAdd() {
      if (this.getPerRoles()) {
        this.reset()
        this.title = '新增用户';
        this.open = true;
        this.showPassword = true;
        this.optionType = 'add';
      }
    },
    // 获取所有有权的角色列表 
    getPerRoles() {
      return this.getRequest('/manage/user/per/roles').then(resp => {
        if (resp) {
          this.perRoles = resp.data;
          return resp;
        }
      });
    },
    // 获取超级管理员角色
    getPerRoleAdmin() {
      return this.getRequest('/manage/user/per/rolesAdmin/1').then(resp => {
        if (resp) {
          this.perRoles = resp.data;
          return resp;
        }
      });
    },
    reset() {
      this.form = {
        userId: undefined,
        username: undefined,
        password: "123456",
        realName: undefined,
        roleId: undefined,
        phone: undefined,
        gender: undefined,
        age: undefined,
      }
      this.resetForm('form')
    },
    // 重置搜索条件
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 搜索
    handleQuery() {
      this.queryParams.page = 1
      this.getData()
    },
    getData() {
      this.loading = true
      this.getRequest(
        '/manage/user/',
        this.addDateRange(this.queryParams, this.dateRange)
      )
        .then((resp) => {
          if (resp) {
            this.userData = resp.data.list
            this.totalCount = Number(resp.data.total)
            this.loading = false
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleSelectionChange(val) {
      this.userIds = val.map((item) => item.userId);

      if (this.userIds.length <= 0) {
        this.buttonState.delDisabled = true
      } else {
        this.buttonState.delDisabled = false
      }

      if (this.userIds.length == 1) {
        this.buttonState.editDisabled = false
      } else {
        this.buttonState.editDisabled = true
      }
    }
  },
  computed: {
    gender() {
      let gender = [
        { label: "男", value: "1" },
        { label: "女", value: "0" },
        { label: "保密", value: "2" },
      ];
      return gender;
    }
  }
}
</script>

<style lang='scss' scoped>
.app-container {
  .filter-container {
    padding-top: 0;
  }
}
</style>